package config

import (
	"fmt"
	"github.com/toolkits/pkg/logger"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

var SysConfig SysConfigS

type SysConfigS struct {
	MysqlConf `yaml:"mysql"`
	RedisConf `yaml:"redis"`
	Logger    `yaml:"logger"`
}

type MysqlConf struct {
	MysqlIp       string `split_words:"true" yaml:"mysql_ip"`
	MysqlPort     string `split_words:"true" yaml:"mysql_port"`
	DbName        string `split_words:"true" yaml:"db_name"`
	MysqlUser     string `plit_words:"true" yaml:"mysql_user"`
	MysqlPassword string `split_words:"true" yaml:"mysql_password"`
	//MysqlPassword string `default:"1234" split_words:"true" yaml:"mysql_password"`
}

// 环境变量定义示例：CROW_MYSQL_IP=127.0.0.1
// 环境变量将覆盖配置文件
// 环境变量引用示例：config.SysConfig.MysqlIp

type RedisConf struct {
	RidesIp       string `split_words:"true" yaml:"rides_ip"`
	RidesPort     string `split_words:"true" yaml:"rides_port"`
	RidesDbNum    int    `split_words:"true" yaml:"rides_db_num"`
	RidesPassword string `split_words:"true" yaml:"rides_password"`
}

type Logger struct {
	LogDir       string `split_words:"true" yaml:"log_dir"`
	LogLevel     string `split_words:"true" yaml:"log_level"`
	LogKeepHours uint   `split_words:"true" yaml:"log_keep_hours"`
	LoggerUse    bool   `split_words:"true" yaml:"log_use"`
}

func init() {
	//给配置项赋值
	SysConfig = *createConfig()
	SysConfig.setConfig()

}

func createConfig() (conf *SysConfigS) {
	conf = new(SysConfigS)
	return conf
}

func (conf *SysConfigS) setConfig() {

	configFileName := getConfigFileName()
	//yamlFile, err := ioutil.ReadFile("./conf/conf.yaml")
	yamlFile, err := ioutil.ReadFile("./conf/" + configFileName)
	fmt.Println("./conf/" + configFileName)
	if err != nil {
		fmt.Println(err)
	}
	err = yaml.Unmarshal(yamlFile, &conf)
	if err != nil {
		fmt.Println(err)

	}
	logger.Debugf("配置项：读取文件配置：%+v\n", SysConfig)
	conf.setDefault()
	logger.Debugf("配置项：覆盖默认值：%+v\n", SysConfig)
}

func (conf *SysConfigS) setDefault() {
	//redis默认值
	if conf.RedisConf.RidesDbNum == 0 {
		conf.RedisConf.RidesDbNum = 1
	}
	if conf.RedisConf.RidesPort == "" {
		conf.RedisConf.RidesPort = "6379"
	}
	if conf.RedisConf.RidesIp == "" {
		conf.RedisConf.RidesIp = "127.0.0.1"
	}
	//mysql默认值
	if conf.MysqlConf.MysqlIp == "" {
		conf.MysqlConf.MysqlIp = "127.0.0.1"
	}
	if conf.MysqlConf.MysqlPort == "" {
		conf.MysqlConf.MysqlPort = "3306"
	}
	if conf.MysqlConf.DbName == "" {
		conf.MysqlConf.MysqlIp = "crow"
	}
	//日志默认值
	if conf.Logger.LogLevel == "" {
		conf.Logger.LogLevel = "INFO"
	}
	if conf.Logger.LogDir == "" {
		conf.Logger.LogDir = "logs"
	}
	if conf.Logger.LogKeepHours == 0 {
		conf.Logger.LogKeepHours = 24
	}
}
